<script setup lang="ts">
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { showToast, showSuccessToast } from 'vant';
import YHeader from '@/components/YHeader.vue';
import type { UploaderFileListItem } from 'vant';
import { createCourse, uploadCourseCover } from '@/api/classroom';
import { useUserStore } from '@/store/user';
const userStore = useUserStore();
const teacherId = userStore.getId || '';


const router = useRouter();
const isSubmitting = ref(false);

// 表单数据
const formData = ref({
  name: '',
  code: '',
  term: '', 
  coverImage: [] as UploaderFileListItem[],
  description: '',
  requirements: '',
  joinCode: '',
  maxStudent: '' 
});

const afterCoverRead = async (fileItem: UploaderFileListItem) => {
  try {
    const fData = new FormData();
    fData.append('cover', fileItem.file as File);

    const res = await uploadCourseCover(fData);
    if (res.code === 2000) {
      const imageUrl = res.data;
      fileItem.url = imageUrl;
      formData.value.coverImage = [fileItem];

      showToast('图片上传成功');
    } else {
      showToast(res.data.msg || '上传失败');
    }
  } catch (error) {
    console.error('图片上传错误：', error);
    showToast('图片上传失败');
  }
};
const onBack = () => {
  router.back();
};


const beforeCoverRead = (file: File) => {
  const allowedTypes = ['image/jpeg', 'image/png'];
  if (!allowedTypes.includes(file.type)) {
    showToast('请上传 JPG 或 PNG 格式的图片');
    return false;
  }
  const maxSize = 2 * 1024 * 1024;
  if (file.size > maxSize) {
    showToast('图片大小不能超过 2MB');
    return false;
  }
  
  return true;
};


const generateJoinCode = () => {
  const code = Math.random().toString(36).substr(2, 6).toUpperCase();
  formData.value.joinCode = code;
};

const onSubmit = async () => {

  if (!formData.value.name) {
    showToast('请输入课程名称');
    return;
  }
  if (formData.value.coverImage.length === 0) {
    showToast('请上传课程封面');
    return;
  }
  

  try {
    isSubmitting.value = true;
    
    const coverImgItem = formData.value.coverImage[0];
    const coverImageUrl = coverImgItem.url || coverImgItem.content || '';

    const payload = {
      name: formData.value.name,
      code: formData.value.code,
      term: formData.value.term, 
      description: formData.value.description,
      requirements: formData.value.requirements,
      coverImage: coverImageUrl,
      joinCode: formData.value.joinCode,
      maxStudent: formData.value.maxStudent
        ? Number(formData.value.maxStudent)
        : undefined,
      teacherId: teacherId,
      
    };
    const res = await createCourse(payload);
    console.log(payload);
    if (res.code === 200) {
      showSuccessToast('课程创建成功');
      router.push('/classroom/list');
    } else {
      showToast(res.data.msg || '创建课程失败');
    }
  } catch (error) {
    console.error('创建课程失败：', error);
    showToast('创建失败，请重试');
  } finally {
    isSubmitting.value = false;
  }
};
</script>
<template>
    <div class="create-classroom">
      <y-header title="创建课程" left-arrow @click-left="onBack" />
      
      <van-form @submit="onSubmit" class="create-form">
        <div class="form-section">
          <div class="section-title">基本信息</div>
          <van-cell-group inset>
            <van-field
              v-model="formData.name"
              name="name"
              label="课程名称"
              placeholder="请输入课程名称"
              :rules="[{ required: true, message: '请输入课程名称' }]"
            />
            
            <van-field
              v-model="formData.code"
              name="code"
              label="课程代码"
              placeholder="请输入课程代码（选填）"
            />
            
            
            <van-field name="term" label="学期">
              <template #input>
                <van-radio-group v-model="formData.term" direction="horizontal">
                  <van-radio name="0">第一学期</van-radio>
                 <van-radio name="1">第二学期</van-radio>
                </van-radio-group>
              </template>
            </van-field>
            

          </van-cell-group>
        </div>

        <div class="form-section">
          <div class="section-title">课程封面</div>
          <div class="cover-upload">
            <van-uploader
              v-model="formData.coverImage"
              :max-count="1"
              :after-read="afterCoverRead"
              :before-read="beforeCoverRead"
            >
              <div class="upload-area" :class="{ 'has-image': formData.coverImage.length > 0 }">
                <template v-if="formData.coverImage.length === 0">
                  <van-icon name="photograph" />
                  <div class="upload-text">上传课程封面</div>
                  <div class="upload-tip">建议尺寸 800x400，JPG、PNG格式</div>
                </template>
                <img v-else :src="formData.coverImage[0].content || formData.coverImage[0].url" alt="课程封面">
              </div>
            </van-uploader>
          </div>
        </div>

        <div class="form-section">
          <div class="section-title">课程简介</div>
          <van-cell-group inset>
            <van-field
              v-model="formData.description"
              name="description"
              type="textarea"
              rows="4"
              placeholder="请输入课程简介，介绍课程内容、目标等"
              :rules="[{ required: true, message: '请输入课程简介' }]"
            />
            
            <van-field
              v-model="formData.requirements"
              name="requirements"
              type="textarea"
              rows="3"
              placeholder="请输入学习要求（选填）"
            />
          </van-cell-group>
        </div>
        
        <div class="form-section">
          <div class="section-title">课程设置</div>
          <van-cell-group inset>
            <van-cell title="允许学生自由加入" center>
              <template #right-icon>
                <van-switch v-model="formData.allowFreeJoin" size="20" />
              </template>
            </van-cell>
            
            <van-cell title="开启作业评分" center>
              <template #right-icon>
                <van-switch v-model="formData.enableAssignmentGrading" size="20" />
              </template>
            </van-cell>
            
            <van-cell title="开启考试功能" center>
              <template #right-icon>
                <van-switch v-model="formData.enableExam" size="20" />
              </template>
            </van-cell>
            
            <van-field
              v-if="!formData.allowFreeJoin"
              v-model="formData.joinCode"
              center
              label="加课验证码"
            >
              <template #button>
                <van-button size="small" type="primary" @click="generateJoinCode">生成</van-button>
              </template>
            </van-field>
            
            <van-field
              v-model.number="formData.maxStudent"
              type="digit"
              label="人数上限"
              placeholder="不填则不限制"
            />
          </van-cell-group>
        </div>
        
        <!-- 提交按钮 -->
        <div class="submit-bar">
          <van-button round block type="primary" native-type="submit" :loading="isSubmitting">
            创建课程
          </van-button>
        </div>
      </van-form>
    </div>
  </template>
  
 
  
  <style scoped>
  .create-classroom {
    background-color: #f7f8fa;
    min-height: 100vh;
    padding-bottom: 80px;
  }
  
  .create-form {
    padding: 16px;
  }
  
  .form-section {
    margin-bottom: 24px;
  }
  
  .section-title {
    margin-bottom: 12px;
    padding-left: 8px;
    font-size: 16px;
    font-weight: 500;
    color: #323233;
    position: relative;
  }
  
  .section-title::before {
    content: '';
    position: absolute;
    left: 0;
    top: 4px;
    bottom: 4px;
    width: 3px;
    background-color: #1989fa;
    border-radius: 1px;
  }
  
  .cover-upload {
    padding: 16px;
    background-color: #fff;
    border-radius: 8px;
  }
  
  .upload-area {
    width: 100%;
    height: 200px;
    border: 2px dashed #dcdee0;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: all 0.3s;
  }
  
  .upload-area:hover {
    border-color: #1989fa;
  }
  
  .upload-area.has-image {
    border: none;
  }
  
  .upload-area.has-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 8px;
  }
  
  .upload-area .van-icon {
    font-size: 48px;
    color: #969799;
  }
  
  .upload-text {
    margin-top: 12px;
    font-size: 16px;
    color: #323233;
  }
  
  .upload-tip {
    margin-top: 8px;
    font-size: 12px;
    color: #969799;
  }
  
  .submit-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 16px;
    background-color: #fff;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  }
  
  :deep(.van-field__label) {
    width: 80px;
  }
  
  :deep(.van-cell-group) {
    margin: 0;
  }
  </style>